import axios from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 5000,
});

//缓存
export function cache(key, val, expire) {
    expire = expire > 0 ? expire : 36000;
    var time = Date.parse(new Date()) / 1000;
    if (val) {
        localStorage.setItem(key, JSON.stringify({ val: val, expire: time + expire }))
        return true
    } else if (val === null) {
        localStorage.removeItem(key)
    } else {
        var json = localStorage.getItem(key)
        try {
            var data = JSON.parse(json)
            if (data.expire <= time) {
                localStorage.removeItem(key)
                return false
            }
            return data.val
        } catch (d) {
            return false;
        }
    }
}


//清理过期缓存
function checkCache() {
    var space = ((1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length) / 1024 / 1024).toFixed(2);
    console.log('存储空间还剩:' + space + 'M');
    //空间不足,清理所有缓存
    if (space <= 0.2) {
        const token = cache('token')
        localStorage.clear()
        if (token) {
            cache('token', token, 3600 * 24 * 30)
        }
    }
    var storage = window.localStorage
    for (var i = 0; i < storage.length; i++) {
        var v = storage.getItem(storage.key(i))
        if (v && v.indexOf('expire') != -1) {
            var data = JSON.parse(v)
            if (data.expire <= (Date.parse(new Date()) / 1000)) {
                localStorage.removeItem(storage.key(i))
            }
        }
    }
}

checkCache()

// 设置请求发送之前的拦截器
request.interceptors.request.use(
    (config) => {
        config.headers["token"] = '';
        config.headers["Content-Type"] = "application/x-www-form-urlencoded";
        // 设置发送之前数据需要做什么处理
        return config;
    },
    (err) => Promise.reject(err)
);

// 设置请求接受拦截器
request.interceptors.response.use(
    (res) => {
        return res;
    },
    (err) => {
        if (err.message.includes("403")) {
            console.error("无权访问，请登录");
            ElMessage.warning("无权访问，请登录");
            return;
        }
        // 判断请求异常信息中是否含有超时timeout字符串
        if (err.message.includes("timeout")) {
            ElMessage.warning("超时了,请重新访问");
            console.error("超时了,请重新访问");
        }
        if (err.message.includes("Network Error")) {
            ElMessage.warning("请检查网络!");
            console.error("请检查网络!");
        }
        return Promise.reject(err);
    }
);

export function useMenu(callback) {
    const data = [
        {
            path: "/dashboard",
            name: "dashboard",
            meta: {
                "name": "控制台"
            },
            component: "index/dashboard",
        },
        {
            path: "/user",
            name: "user",
            component: "user/index",
            meta: {
                name: "用户管理",
                hidden: false
            },
            children: [
                {
                    path: "/user/index",
                    name: "user-index",
                    meta: {
                        "name": "用户列表"
                    },
                    component: "user/add",
                },
                {
                    path: "/user/add",
                    name: "user-add",
                    meta: {
                        "name": "添加用户"
                    },
                    component: "user/add",
                }
            ]
        },
        {
            path: "/order",
            name: "order",
            meta: {
                "name": "订单管理"
            },
            component: "order/index",
        },
        {
            path: "/jieqi",
            name: "jieqi",
            meta: {
                "name": "节气管理"
            },
            component: "jieqi/index",
        },
    ]
    callback(data)
}